package com.imooc.aspect;


import com.imooc.annotation.Time;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.Signature;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;

import java.lang.reflect.Method;


/**
 * 时间统计切面
 *
 * 	在spring中，默认是按照切面名称的字典顺序进行执行的，但是如果想自己改变具体的执行顺序的话，可以使用@Order注解来解决，数值越小，优先级越高。
 *
 */

@Aspect
@Order(1)
@Component
@Slf4j
public class TimeAspect {

    /**
     *  切入点也可以切注解
     */
    @Pointcut("@annotation(com.imooc.annotation.Time)")
    public void pointCut(){};

    @Around("pointCut()")
    public Object timeAround(ProceedingJoinPoint proceedingJoinPoint) throws Throwable {
        Signature signature = proceedingJoinPoint.getSignature();
        Method method = ((MethodSignature) signature).getMethod();
        Time time = method.getAnnotation(Time.class);
        long beginTime = System.currentTimeMillis();
        Object object = proceedingJoinPoint.proceed();
        log.error(method.getName() + "_TotalTime: " + (System.currentTimeMillis() - beginTime));
        return object;
    }

}
